package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/*
* 亿奇达
* */
@Slf4j
public class Plugin_ECARD_P021 implements ChannelService {

    @Override
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }



    @Override
    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data) {

        try {
            String AccountVal = String.valueOf(data.get("AccountVal"));
            List<String> accounts=new ArrayList<>();
            accounts.add(AccountVal);

            LinkedHashMap<String, Object> params = new LinkedHashMap<>();
            params.put("commodityId",String.valueOf(data.get("SUPProductId")));
            params.put("external_orderno",String.valueOf(data.get("ChannelOrderCode")));
            params.put("buyCount","1");
            params.put("externalSellPrice","0");
            params.put("template",accounts);//  ["URL编码（1234567)"]

            long timestampInSeconds = System.currentTimeMillis();
            String secretKey = apiConfig.getString("secretKey");
            String paramsStr = JSON.toJSONString(params);
            String sign = getMd5Hash(String.valueOf(timestampInSeconds), paramsStr, secretKey);

            String userId = apiConfig.getString("UserId");

            StringBuffer url = apiConfig.getObject("SubmitUrl", StringBuffer.class);
            url.append("?timestamp=")
                    .append(timestampInSeconds)
                    .append("&userName=")
                    .append(userId)
                    .append("&sign=")
                    .append(sign);

            String sendPost = sendPost(String.valueOf(url), params);
            JSONObject jsonObject = JSONObject.parseObject(sendPost);
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("msg");
            if (code.equals("200") || code.equals("1001") || code.equals("513")) {
                return ChannelResult.IN_PROCESS("订单提交成功，权益充值中");
            }
            if(code.equals("508") || code.equals("509") || code.equals("511")){
                return ChannelResult.error(msg);
            }
            return ChannelResult.FAILED("充值失败##"+msg);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("亿奇达提交订单接口错误：",e);
            return  ChannelResult.error("亿奇达提交订单接口错误");
        }

    }

    @Override
    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {

        try {
            long timestampInSeconds = System.currentTimeMillis();
            String secretKey = apiConfig.getString("secretKey");
            LinkedHashMap<String, Object> params = new LinkedHashMap<>();
            params.put("external_orderno",String.valueOf(data.get("ChannelOrderCode")));
            String sign = getMd5Hash(String.valueOf(timestampInSeconds), JSON.toJSONString(params), secretKey);
            String userId = apiConfig.getString("UserId");
            StringBuffer url = apiConfig.getObject("QueryUrl", StringBuffer.class);
            url.append("?timestamp=")
                    .append(timestampInSeconds)
                    .append("&userName=")
                    .append(userId)
                    .append("&sign=")
                    .append(sign);

            String result = sendPost(String.valueOf(url), params);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("msg");
            String dataParams = jsonObject.getString("data");
            JSONObject dataObj = JSONObject.parseObject(dataParams);
            String status = dataObj.getString("status");
            if(code.equals("200")){
                if(status.equals("4")){
                    return ChannelResult.success("充值成功");
                }
                if (status.equals("5")) {
                    return ChannelResult.FAILED("充值失败");
                }
                return ChannelResult.IN_PROCESS("充值中");
            }
        return ChannelResult.error(msg);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("亿奇达查询订单接口错误：",e);
            return  ChannelResult.error("亿奇达查询订单接口错误");

        }

    }


    @Override
    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");
    }



    public static String getMd5Hash(String timestamp, String data, String key) {
        String message = timestamp + data + key;
        byte[] md5Bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md5Bytes = md.digest(message.getBytes());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        return bytesToHex(md5Bytes);
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            hexString.append(String.format("%02x", b));
        }
        return hexString.toString();
    }



    public static String sendPost(String url, Map<String,Object> param) {
        String result = "";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(param),"utf-8"));
            log.info("httpPost请求："+url+"?"+JSONObject.toJSONString(param));
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                result= EntityUtils.toString(responseEntity);
                log.info("httpPost请求返回："+JSONObject.toJSONString(result));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  result;
    }

}
